<template>
	<view class="app-container">
		<scroll-view class="content" scroll-y="true">
			<cell-message>
				<template v-slot:left>
					<image class="icon-avatar" src="../../static/images/logo.png" mode=""></image>
				</template>
			</cell-message>
		</scroll-view>

	</view>
</template>

<script>
	import CellMessage from '../../components/cell-message.vue'
	import {
		sendObj,
		sendStr
	} from '../../utils/websocket.js'
	import {
		getUser
	} from '../../utils/auth.js'
	export default {
		components: {
			CellMessage
		},
		data() {
			return {
				heardTimer: null,
				closeCoonTimer: null,
				uid: ''
			}
		},
		onLoad() {
			this.uid = getUser().userInfo.userId
			this.initWebSocket()
		},
		methods: {
			initWebSocket() {
				// 创建socket连接对象
				uni.connectSocket({
					// url: 'wss://localhost:8889/',
					url: 'wss://websocketyfkdu.cn1.utools.club/',
					complete: () => {},
				});
				// socket连接打开，发送新的用户信息 发送心跳信息
				uni.onSocketOpen((res) => {
					console.log('WebSocket连接已打开！')
					let system = uni.getSystemInfoSync()
					// 发送新用户连接信息
					sendObj({
						did: system.deviceId,
						type: 1,
						uid: this.uid
					})
					// 发送心跳
					this.sendHeard()
					// 关闭连接
					this.closeCoon()
				});

				// 检测socket服务器返回的信息 如果没有心跳 这关闭连接清空连接定时器 关闭连接 如果是心跳不做处理 
				uni.onSocketMessage((resp) => {
					let data = resp.data
					if (data == "heard") {
						clearTimeout(this.closeCoonTimer)
						this.closeCoon()
						return;
					}
					// 根据类型做响应
					let jsonData = JSON.parse(data)
					// console.log('响应的jsonData:', jsonData)
					if (jsonData.type == 6) {
						uni.clearStorageSync()
						uni.showToast({
							icon: 'none',
							title: '在另一台设备上登录'
						})
						uni.reLaunch({
							url: '/pages/login/login'
						})
					} else if (jsonData.type == 3) {
						console.log('jsonData发送了',jsonData);
						uni.$emit('sendMsg', jsonData)
					}


				});
				// 检测到socket关闭 清空心跳 ，发起重连
				uni.onSocketClose((res) => {
					console.log('WebSocket 已关闭！');
					clearInterval(this.heardTimer)
					this.reCoon()

				})
				// socket发生错误

			},
			// 发送心跳
			sendHeard() {
				let system = uni.getSystemInfoSync()
				this.heardTimer = setInterval(() => {
					sendObj({
						did: system.deviceId,
						type: 2
					})
				}, 5000)
			},
			// 关闭socket
			closeCoon() {
				this.closeCoonTimer = setTimeout(() => {
					uni.closeSocket();
				}, 10000)
			},
			// 
			reCoon() {
				console.log("重连中...");
				setTimeout(() => {
					this.initWebSocket()
				}, 5000)
			}
		}
	}
</script>

<style>
	.content {
		background-color: #fff;
		height: 100%;
	}
</style>
